package backend

import (
	"bytes"
	"context"
	"dockerview/backend/utils"
	"errors"
	"fmt"
	"gitee.com/openeuler/go-gitee/gitee"
	"os"
	"os/exec"
)

type UpdateApp struct {
	currentVersion string
	newVersion     string
	appBinaryPath  string
	dataFolderPath string
	app            *App
}

func (u *UpdateApp) Run() {
	var err error

	u.currentVersion = u.app.AppMeta.AppVersion
	u.newVersion = u.GetLatestRelease()
	u.appBinaryPath, err = os.Executable()
	if err != nil {
		u.app.log.Error(fmt.Sprintf("无法收集app二进制文件的路径. 原因: %s", err))
	}
	u.dataFolderPath = u.app.AppMeta.AppDataDir

	err = u.TriggerUpdate()
	if err != nil {
		u.app.log.Error(fmt.Sprintf("无法更新app. 原因: %s", err))
		u.app.SendError("无法更新app. 原因: ", err)
	}
}

func (u *UpdateApp) Check() (result string) {
	u.currentVersion = u.app.AppMeta.AppVersion
	u.newVersion = u.GetLatestRelease()
	return utils.VarsionDiff(u.newVersion, u.currentVersion)
}

func (u *UpdateApp) TriggerUpdate() error {
	_, fileExt := utils.GetUserOS()
	main := u.dataFolderPath + "/update" + fileExt
	args := []string{"download_url=" + downloadURL, "-init_dag_path=" + u.dataFolderPath, "-init_molly_path=" + u.appBinaryPath, "-new_version=" + u.newVersion, "-upgrade=" + "true"}

	cmd := exec.Command(main, args...)
	u.app.log.Info(fmt.Sprintf("正在运行命令 : %s", cmd))

	var stderr bytes.Buffer
	cmd.Stderr = &stderr // Captures STDERR

	err := cmd.Run()
	if err != nil {
		errFormatted := fmt.Sprint(err) + ": " + stderr.String()
		return errors.New(errFormatted)
	}
	return nil
}

func (u *UpdateApp) GetLatestRelease() string {
	cfg := gitee.NewConfiguration()
	client := gitee.NewAPIClient(cfg)
	ctx := context.Background()
	var release gitee.Release
	release, _, err := client.RepositoriesApi.GetV5ReposOwnerRepoReleasesLatest(ctx, APP_OENER, APP_REPO, nil)
	if err != nil {
		u.app.log.Error(fmt.Sprintf("最后版本获取失败. 原因: %s", err))
	}
	return release.TagName

}
